// @ts-ignore
import { fail } from 'mobx-miniprogram/lib/internal'
import { obtainHighSeasOrders, ReceivingOrders, ReOrderSearch } from '../../../http/api/orderService'
import Toast from 'tdesign-miniprogram/toast/index'
import Message from 'tdesign-miniprogram/message/index'
import { throttle } from '../../../utils/util'

Page({
    data: {
        activeIndex: 0,
        orderInfo: {},
        orderList: [], // 公海订单
        page: 1,
        size: 2,
        total: 0,
        isAll: false
    } as any,

    /**
     * 抢单
     */
    grabAnOrder: throttle(async function (e: any) {
        const orderStatus = e.currentTarget.dataset.orderstatus
        const orderInfo = e.currentTarget.dataset.orderinfo
        console.log(orderInfo, orderStatus, e)
        const res: any = await ReceivingOrders(orderInfo.order_id)
        console.log(res, '---ReceivingOrders')
        if (res.msg.includes('司机预存保证金不足')) {
            Message.warning({
                context: this,
                offset: [20, 32],
                duration: 5000,
                icon: false,
                content: res.msg
            })
            wx.switchTab({
                url: '/pages/driver/my/my'
            })
            return
        }
        if (res.data[0].msg != undefined && res.data[0].msg == '抢单成功') {
            this.setData({
                activeIndex: 1
            })
            const arr = await this.Re_Order_Search(1)

            this.setData({
                orderList: arr,
                orderInfo: {
                    ...orderInfo,
                    order_type: 1
                }
            })
            Toast({
                context: this,
                selector: '#t-toast',
                message: '抢单成功'
            })
        }
    }),

    async weizhi(orderInfo: any) {
        let tis = this
        let userLocation = false
        let userLocationBackground = false
        wx.getSetting({
            success: async (ress: any) => {
                for (let i in ress.authSetting) {
                    if (i == 'scope.userLocation' && ress.authSetting[i]) {
                        userLocation = ress.authSetting[i]
                    }
                    if (i == 'scope.userLocationBackground' && ress.authSetting[i]) {
                        userLocationBackground = ress.authSetting[i]
                    }
                }
                console.log(userLocation)
                console.log(userLocationBackground)
                if (!userLocation && !userLocationBackground) {
                    wx.showToast({
                        title: '点击右上角设置\r\n开打后台定位',
                        icon: 'error',
                        duration: 2000
                    })
                }
            },
            fail: res => {
                console.log(res)
            }
        })
    },

    toDetail(e: any) {
        let tis = this
        const orderStatus = e.currentTarget.dataset.orderstatus
        const orderInfo = e.currentTarget.dataset.orderinfo
        wx.authorize({
            scope: 'scope.userLocationBackground',
            success: res => {
                console.log(orderInfo, orderStatus, e)
                wx.navigateTo({
                    url: `/pages/driver/detail/detail?orderStatus=${orderStatus}&info=${JSON.stringify(orderInfo)}`
                })
            },
            fail: res => {
                tis.weizhi(orderInfo)
            }
        })
    },

    async onTabsChange(event: any) {
        this.setData({
            page: 1,
            activeIndex: event.detail.value
        })
        let arr: any = []
        if (event.detail.value == 0) {
            arr = await this.getOrderList()
        } else {
            arr = await this.Re_Order_Search(event.detail.value)
        }
        console.log(arr, '----arr')
        this.setData({
            orderList: arr
        })
    },

    async getOrderList() {
        const { page } = this.data
        const res: any = await obtainHighSeasOrders(page)
        const resMap: any = []
        if (res.data[0].errmsg != 'undefined') {
            res.data.forEach((item: any) => {
                resMap.push({
                    ...item,
                    order_distance: item.order_distance.toFixed(2)
                })
            })
        }
        console.log(res, resMap, 'obtainHighSeasOrders')

        this.setData({
            total: res.count
        })
        return resMap
    },

    async Re_Order_Search(index: number) {
        const { page } = this.data
        const res: any = await ReOrderSearch(page, 2, index)
        const resMap: any = []
        if (res.data[0].errmsg != 'undefined') {
            res.data.forEach((item: any) => {
                if (item.order_distance != null) {
                    resMap.push({
                        ...item,
                        order_distance: item.order_distance.toFixed(2)
                    })
                }
            })
        }
        console.log(resMap, 'ReOrderSearch')

        this.setData({
            total: res.count
        })
        return resMap
    },
    async getList() {
        this.setData({
            orderList: []
        })
        let arr: any = []
        if (this.data.activeIndex == 0) {
            arr = await this.getOrderList()
        } else {
            arr = await this.Re_Order_Search(this.data.activeIndex)
        }
        this.setData({
            orderList: arr
        })
    },
    async onShow() {
        this.setData({
            page: 1
        })
        this.getList()
    },

    onLoad() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
        this.setData({
            page: 1,
            size: 2,
            isAll: false
        })

        await this.getList()

        //停止下拉刷新
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    async onReachBottom() {
        let { page, size, total } = this.data

        if (page * size >= total) {
            wx.showToast({
                title: '到底啦～'
            })
            return
        }
        page++
        this.setData({
            page
        })
        let arr: any = []
        if (this.data.activeIndex == 0) {
            arr = await this.getOrderList()
        } else {
            arr = await this.Re_Order_Search(this.data.activeIndex)
        }

        this.setData({
            orderList: [...this.data.orderList, ...arr]
        })
    }
})
